package com.xiyu.service.repository.bed.bed;

import com.xiyu.service.model.bed.bed.BedInfoFetcher;
import com.xiyu.service.model.bed.bed.BedTypeFetcher;
import com.xiyu.service.model.bed.room.RoomInfoFetcher;
import com.xiyu.service.model.bed.room.RoomTypeFetcher;
import com.xiyu.service.vo.bed.bedInfo.BedInfoPageQueryInput;
import com.xiyu.service.model.bed.bed.BedInfo;
import com.xiyu.service.model.bed.bed.BedInfoTable;
import org.babyfish.jimmer.spring.repository.JRepository;
import org.babyfish.jimmer.Page;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Optional;

public interface BedInfoRepository extends JRepository<BedInfo, Long> {
    BedInfoTable bedInfoTable = BedInfoTable.$;

    Optional<BedInfo> findFirstByBedName(String bedName);

    Optional<BedInfo> findFirstByBedNameAndIdNot(String bedName, Long id);

    default List<BedInfo> findByRoomId(Long roomId){
        return sql().createQuery(bedInfoTable)
                .where(bedInfoTable.roomId().eq(roomId))
                .select(bedInfoTable.fetch(BedInfoFetcher.$.allTableFields().bedType(BedTypeFetcher.$.allTableFields())))
                .execute();
    };

    default Page<BedInfo> pageQuery(BedInfoPageQueryInput inputVO){
        return sql().createQuery(bedInfoTable)
                .whereIf(StringUtils.hasText(inputVO.getBedName()), () ->  bedInfoTable.bedName().like(inputVO.getBedName()))
                .whereIf(inputVO.getBedTypeId() != null, bedInfoTable.bedTypeId().eq(inputVO.getBedTypeId()))
                .whereIf(StringUtils.hasText(inputVO.getRoomName()), () -> bedInfoTable.room().roomName().like(inputVO.getRoomName()))
                .whereIf(inputVO.getBuildingId() != null, bedInfoTable.room().buildingId().eq(inputVO.getBuildingId()))
                .orderBy(bedInfoTable.id().desc())
                .select(bedInfoTable.fetch(BedInfoFetcher.$.allTableFields()
                        .room(RoomInfoFetcher.$.allTableFields().roomType(RoomTypeFetcher.$.allTableFields()))
                        .bedType(BedTypeFetcher.$.allTableFields())))
                .fetchPage(inputVO.getPageNo() - 1, inputVO.getPageSize());
    }


}